package dao

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"time"
)

type LogsDao interface {
	SaveLog(logs *Logs) error
	List(ctx *gin.Context, page, size int) ([]*Logs, error)
	FindLogsCount(ctx *gin.Context) int64
}

type GormLogsDao struct {
	db *gorm.DB
}

func (g *GormLogsDao) FindLogsCount(ctx *gin.Context) int64 {
	var logs []*Logs
	var count int64
	if rs := g.db.WithContext(ctx).Find(&logs).Count(&count); rs.Error != nil {
		zap.S().Errorf("查询日志总条数失败:%s", rs.Error)
		return 0
	}
	return count
}

func (g *GormLogsDao) List(ctx *gin.Context, page, size int) ([]*Logs, error) {
	var logs []*Logs
	var err error
	if page != 0 && size != 0 {
		// 计算偏移量
		offset := (page - 1) * size
		// 使用分页参数进行查询
		err := g.db.WithContext(ctx).Where("language_id is not null").Offset(offset).Limit(size).Find(&logs).Error
		if err != nil {
			return nil, err
		}
	} else {
		if rs := g.db.WithContext(ctx).Find(&logs); rs.Error != nil {
			return nil, rs.Error
		}
		return logs, nil
	}
	return logs, err
}

func (g *GormLogsDao) SaveLog(logs *Logs) error {
	result := g.db.Create(logs)
	if result.Error != nil {
		zap.S().Errorf("写入日志失败: %v", result.Error)
		return result.Error
	}
	zap.S().Infof("写入日志成功: %v", logs)
	return nil
}
func NewLogsDao(db *gorm.DB) LogsDao {
	return &GormLogsDao{db: db}
}

type Logs struct {
	ID         uint      `gorm:"primaryKey;autoIncrement"`
	UserID     string    `gorm:"column:user_id;not null"`
	Action     string    `gorm:"column:action;not null"`
	Type       string    `gorm:"not null;size:50"`
	Timestamp  time.Time `gorm:"column:timestamp"`
	Details    string    `gorm:"column:details"`
	LanguageID string    `gorm:"column:language_id;size:50"`
}

func (*Logs) TableName() string {
	return "logs"
}
